package com.yicong.ants.manager.js;

import android.content.Context;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;

import com.yicong.ants.utils.L;
import com.yicong.ants.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 注入 webview 展示图片
 */
public class ShowPicRelation {

    public static final String NAME = "rzj";
    private static final String TAG = ShowPicRelation.class.getSimpleName();
    private Context mContext;
    private List<String> mUrls;

    private ShowPicRelation() {
    }

    public ShowPicRelation(Context context) {
        this.mContext = context;
    }

    /**
     * 获取 Img 的 JavaScript
     *
     * @return
     */
    public static String getJsForImg() {
        return "javascript:(function  pic(){" +
            "var imgList = \"\";" +
            "var imgs = document.getElementsByTagName(\"img\");" +
            "for(var i=0;i<imgs.length;i++){" +
            "var img = imgs[i];" +
            "imgList = imgList + img.src +\";\";" +
            "img.onclick = function(){" +
            "window.rzj.openImg(this.src);" +
            "}" +
            "}" +
            "window.rzj.getImgArray(imgList);" +
            "})()";
    }

    public static String getJsForNewsDetails() {
        return "javascript:(function  pic(){" +
            "var imgList = \"\";" +
            "var imgs = document.getElementById(\"content\").getElementsByTagName(\"img\");" +
            "for(var i=0;i<imgs.length;i++){" +
            "var img = imgs[i];" +
            "imgList = imgList + img.src +\";\";" +
            "img.onclick = function(){" +
            "window.rzj.openImg(this.src);" +
            "}" +
            "}" +
            "window.rzj.getImgArray(imgList);" +
            "})()";
    }

    /**
     * JS中点击图片执行的Java代码
     */
    @JavascriptInterface
    public void openImg(String url) {
        //传到展示图片的viewPager
/*        Intent intent = new Intent(mContext, ImageViewPagerActivity.class);
        intent.putExtra(ImageViewPagerActivity.POSITION, mUrls.indexOf(url));
        intent.putStringArrayListExtra(ImageViewPagerActivity.IMG_URLS, (ArrayList<String>) mUrls);
        mContext.startActivity(intent);*/
    }

    @JavascriptInterface
    public void showToast(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            ToastUtils.showShort(mContext, msg);
        }
    }

    /**
     * 页面加载时JS调用的Java代码
     */
    @JavascriptInterface
    public void getImgArray(String urlArray) {
        L.e(TAG, urlArray);
        String content = urlArray.substring(0, urlArray.length() - 1);
        String[] urls = content.split(";");//url拼接成的字符串，有分号隔开
        if (null == mUrls) {
            mUrls = new ArrayList<>();
        } else if (mUrls.size() > 0) {
            mUrls.clear();
        }
        for (String url : urls) {
            mUrls.add(url);
        }
    }
}
